package br.com.searchpeople.asynctask;

import java.io.IOException;

import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import br.com.searchpeople.activity.TimelineActivity;
import br.com.searchpeople.database.SingletonAccountBD;
import br.com.searchpeople.model.UserModel;

import com.savagelook.android.UrlJsonAsyncTask;

public class RegisterTask extends UrlJsonAsyncTask {
	private String user_login;
	private String user_password;
	private String confirm_password;
	private String nickname;
	private Context context;
	public RegisterTask(Context context, String user_login, String user_password, String confirm_password, String nickname) {
		super(context);
		this.user_login = user_login;
		this.user_password = user_password;
		this.confirm_password = confirm_password;
		this.nickname = nickname;
		this.context = context;
	}

	@Override
	protected JSONObject doInBackground(String... urls) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(urls[0]);
		JSONObject holder = new JSONObject();
		JSONObject userObj = new JSONObject();
		String response = null;
		JSONObject json = new JSONObject();

		try {
			try {
				json.put("success", false);
				json.put("info", "Alguma coisa deu erro. Tente novamente!");

				userObj.put("email", user_login);
				userObj.put("password", user_password);
				userObj.put("password_confirmation", confirm_password);
				userObj.put("name", nickname);
				holder.put("user", userObj);
				StringEntity se = new StringEntity(holder.toString());
				post.setEntity(se);

				post.setHeader("Accept", "application/json");
				post.setHeader("Content-Type", "application/json");

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				response = client.execute(post, responseHandler);
				json = new JSONObject(response);
			} catch (HttpResponseException e) {
				e.printStackTrace();
				Log.e("ClientProtocol", "" + e);
			} catch (IOException e) {
				e.printStackTrace();
				Log.e("IO", "" + e);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("JSON", "" + e);
		}
		return json;
	}

	@Override
	protected void onPostExecute(JSONObject json) {

		try {
			if (json.getBoolean("success")) {
				int user_id = json.getJSONObject("data").getInt("user_id");
				String authtoken = json.getJSONObject("data").getString("auth_token");
				UserModel user = new UserModel(user_login, user_password, confirm_password, nickname, authtoken);
				SingletonAccountBD.getInstance().addAccount(context.getApplicationContext(), user);
				
				SharedPreferences settings = context.getSharedPreferences("general",Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = settings.edit();
				
				try {
					editor.putString("login", user_login);
					editor.putString("AuthToken", authtoken);
					editor.putInt("user_id", user_id);
//					editor.putString("nickname", flagNickname);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					editor.commit();
				}	
				
				// direciona para o timeline
				context.startActivity(new Intent(context.getApplicationContext(),
						TimelineActivity.class));
				((Activity) context).finish();
				createSpecificNotificationToast(json.getString("info"));			
			}
			
		} catch (Exception e) {
			createSpecificNotificationToast(e.getMessage());
		} finally {
			super.onPostExecute(json);
		}
	}
	
	private void createSpecificNotificationToast(String arg0) {
		Context context = this.context.getApplicationContext();
		CharSequence text = arg0;
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
}